package com.oedtech.esl.service.securityService;

import com.oedtech.esl.json.JsonResult;
import com.oedtech.esl.model.sys.User;
import com.oedtech.esl.model.sys.UserRole;
import com.oedtech.esl.model.sys.UserStore;
import com.oedtech.esl.repository.sys.UserDao;
import com.oedtech.esl.repository.sys.UserRoleDao;
import com.oedtech.esl.repository.sys.UserStoreDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.security.Principal;
import java.util.*;

@Service
public class UserNomalService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private UserStoreDao userStoreDao;



    public void deleteUser(Long []userIDs){
        List<Long>list= Arrays.asList(userIDs);
        userDao.deleteUsersById(list);
    }

    @Transactional
    public void saveRoleRelate(List<Long>roleIDs,Long userId,String username){
        userRoleDao.deleteUserRole(userId);
        List<UserRole> userRoleList = new ArrayList<>();
        for(Long roleId:roleIDs){
            UserRole userRole=new UserRole();
            userRole.setRoleId(roleId);
            userRole.setUserId(userId);
            userRoleList.add(userRole);
        }
        userRoleDao.saveAll(userRoleList);
        userDao.relateUser(username, userId);
    }
    @Transactional
    public void saveStoreRelate(List<String>storeCodes,Long userId,String username){

        userStoreDao.deleteUserRole(userId);
        List<UserStore> userStoreList = new ArrayList<>();
        for(String storeCode:storeCodes){
            UserStore userStore = new UserStore();
            userStore.setStoreCode(storeCode);
            userStore.setUserId(userId);
            userStoreList.add(userStore);
        }
        userStoreDao.saveAll(userStoreList);
        userDao.relateUser(username, userId);

    }

    /**
     * 新增或修改用户
     * @param user
     * @return
     */
    public JsonResult AddOrChangeUser(User user){
        if(user.getUsername()==null||user.getUsername().length()<4)return new JsonResult("error","用户名不小于4位");

        if(user.getPassword()==null||user.getPassword().length()<6)return new JsonResult("error","密码不小于6位");
        Authentication auth= SecurityContextHolder.getContext().getAuthentication();
        String username=auth.getName();
        if(user.getId()==null) {
            if (userDao.findByUsername(user.getUsername()) != null) return new JsonResult("error", "用户名已存在");

            String password = user.getPassword();
            user.setPassword(new BCryptPasswordEncoder().encode(password));   //密码加密
        }

//            Integer sourceFlag=userDao.findSourceFlagByUsername(username);//获取本当前登陆的用户下的资源标识
            Map<String,Object> map=userDao.findUserByUsername(username);
            Integer sourceFlag=Integer.valueOf(map.get("sourceFlag").toString());
            Date expireTime=(Date)map.get("expireTime");
            if(sourceFlag==0){
                if(user.getSourceFlag()==null)return new JsonResult("error","资源标识不能空");
            }else{
                user.setExpireTime(expireTime);
                user.setSourceFlag(sourceFlag);
                user.setStatus(0);
            }

        user.setModifyTime(new Date());
        user.setModifyWho(username);
        userDao.save(user);
        return new JsonResult("success","保存成功");
    }

    /**
     * 修改密码
     * @param id
     * @param password
     * @param username
     * @return
     */
    public JsonResult changePwd(Long id, String password, String username){

        if(id==null)return new JsonResult("error","用户不存在");
        if(password==null||password.length()<6)return new JsonResult("error","密码不能小于6位");
        password=new BCryptPasswordEncoder().encode(password);   //密码加密
        if(userDao.changePassword(password,id,username)>0){
            return new JsonResult("success",null);
        }
        return new JsonResult("error","操作失败");
    }

}
